<template>
  <el-form v-if="$slots.queryItem" ref="formEl" class="flex width-all" :model="props.queryFormData" @keyup.enter="emits('query')">
    <div class="form-box flex1">
      <el-row class="flex flex1 width-all">
        <slot name="queryItem"></slot>
      </el-row>
    </div>
    <div class="btn-box mgl30 flex">
      <el-popover v-if="$slots.moreQuery" placement="bottom-end" :width="800" trigger="click" :offset="-5" @show="isShowMore = true" @hide="isShowMore = false">
        <template #reference>
          <div class="more-query mgt5 mgr30 pointer">
            <span class="mgr5">更多条件</span>
            <el-icon v-if="!isShowMore"><ArrowDown /></el-icon>
            <el-icon v-else><ArrowUp /></el-icon>
          </div>
        </template>
        <div>
          <slot name="moreQuery"></slot>
        </div>
      </el-popover>

      <el-button type="primary" @click="handleQuery">查询</el-button>
      <el-button type="primary" plain @click="handleReset">重置</el-button>
    </div>
  </el-form>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import type { FormInstance } from 'element-plus'

  interface IEmits {
    (e: 'query'): void
  }

  const props = defineProps({
    queryFormData: {
      type: Object,
      default: () => ({})
    }
  })

  const emits = defineEmits<IEmits>()

  const formEl = ref<FormInstance | null>()

  const isShowMore = ref(false)

  /**----------------------------methods----------------------------------------------------------------------- */

  const handleQuery = () => {
    formEl.value?.validate(v => {
      if (!v) return
      emits('query')
    })
  }

  const handleReset = () => {
    // 手动重置
    if (props.queryFormData?.params) {
      for (const k in props.queryFormData.params) {
        // eslint-disable-next-line vue/no-mutating-props
        props.queryFormData.params[k] = ''
      }
    }

    formEl.value?.resetFields()
    emits('query')
  }
</script>

<style scoped lang="less">
  .more-query {
    color: var(--el-color-primary);
  }
</style>
